import Koa, { Context } from "koa";
import koaBody from "koa-body";
import koaRouter from "koa-router";
import addRouter from "./utils/routes";
import logger from "koa-logger";
import log4js from "log4js";
import { ResultHandler } from './middleware/resultHandler'
import chalk from "chalk";
import cors from "koa2-cors";

import { init as initDB,Counter} from "./db";
import fs from "fs"
import path from "path"


const app = new Koa();
app.use(cors());
const router = new koaRouter();

const homePage = fs.readFileSync(path.join(__dirname, "index.html"), "utf-8");

// 首页
router.get("/", async (ctx:any) => {
  ctx.body = homePage;
});

// 更新计数
router.post("/api/count", async (ctx:any) => {
  const { request } = ctx;
  const { action } = request.body;
  if (action === "inc") {
    await Counter.create();
  } else if (action === "clear") {
    await Counter.destroy({
      truncate: true,
    });
  }

  ctx.body = {
    code: 0,
    data: await Counter.count(),
  };
});

// 获取计数
router.get("/api/count", async (ctx:any) => {
  const result = await Counter.count();

  ctx.body = {
    code: 0,
    data: result,
  };
});

// 小程序调用，获取微信 Open ID
router.get("/api/wx_openid", async (ctx:any) => {
  if (ctx.request.headers["x-wx-source"]) {
    ctx.body = ctx.request.headers["x-wx-openid"];
  }
});

const port = 27081;
const log4 = log4js.getLogger();
log4.level = "debug";

//日志打印
app.use(logger(info => {
  log4.debug(info);
}));

app.use(koaBody());

app.use(async (ctx, next) => {
  await next()
  // log4.debug(chalk.green('请求路径:  ') + ctx.request.url);
  log4.debug(chalk.green('请求body:  ') + JSON.stringify(ctx.request.body));
  log4.debug(chalk.green('返回数据:  ') + JSON.stringify(ctx.body));
  // log4.debug('请求body:  ' + JSON.stringify(ctx.request.body));
  // log4.debug('返回数据:  '+ JSON.stringify(ctx.body));
})

app.use(ResultHandler());
//加载路由
addRouter(router);
//启动路由
app.use(router.routes()).use(router.allowedMethods());

app.use(async (ctx: Context) => {
  log4.error(`404 ${ctx.message} : ${ctx.href}`);
  // console.log("打印404",ctx.message,ctx.href)
  ctx.status = 404;
  ctx.body = "404! api not found !";
  // console.log("打印404",ctx.body)
  ctx.throw(404,"404! api not found !",{ msg: "404! api not found !" })
});

// koa already had middleware to deal with the error, just register the error event
app.on("error", (err, ctx: Context) => {
  log4.error(err); //log all errors
  ctx.status = 500;
  if (ctx.app.env !== "development") {
    //throw the error to frontEnd when in the develop mode
    ctx.res.end(err.stack); //finish the response
  }
});

async function bootstrap() {
  await initDB();
  app.listen(port, () => {
    log4.info(chalk.green("启动成功", `http://127.0.0.1:${port}`));
  });
}
bootstrap();